package com.mx.socket;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

import com.mx.fs.FileMeta;
import com.mx.fs.FolderItem;
import com.mx.fs.NameItem;
import com.mx.fs.OwnerItem;
public class Client {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Socket socket;
		try {
			Selector selector = Selector.open();
			// connect to the server
			SocketChannel sc = SocketChannel.open(new InetSocketAddress("localhost", 8888));
			sc.configureBlocking(false);
//			selector = selector.wakeup();
			sc.register(selector, SelectionKey.OP_READ);
			FileInputStream fs = new FileInputStream(new File("/media/Elements/学习/电子书/EJB3.pdf"));
//			FileInputStream fs = new FileInputStream(new File("/home/miao/1"));
			FileChannel fc = fs.getChannel();
			System.out.println("size of file:" + fs.available());
//			System.out.println(fc.transferTo(0, 2163908, sc));
			long count = 0;
			
			
			//put the file info into buffer and send to server
			FileMeta meta = new FileMeta();
			meta.addMetaItem(new NameItem("EJB3.pdf"));
			meta.addMetaItem(new FolderItem("/"));
			meta.addMetaItem(new OwnerItem("miao"));
			sc.write(meta.toByteBuffer());
			
			/*These codes works well, now trying another code segment...
			byte[] name = Arrays.copyOf("设计模式漫谈.ppt".getBytes(), 100);
			ByteBuffer buffer = ByteBuffer.allocate(100);
			buffer.put(name);
			buffer.flip();
			sc.write(buffer);
			buffer.compact();*/
			while(true){
				count = count + fc.transferTo(count, fs.available(), sc);
				
				if (count == fs.available()){
					break;
				}
			}

			fc.close();
			fs.close();
			
			
			
			
			/*
			socket = new Socket("localhost", 8888);
			InputStream in = socket.getInputStream();
			OutputStream out = socket.getOutputStream();
			FileInputStream fs = new FileInputStream(new File("/media/Elements/学习/电子书/EJB3.pdf"));			
			byte[] buffer = new byte[40960];
			int count = 0;
			while(true){
				count = fs.read(buffer);
				if (count == -1){
					break;
				}
				out.write(buffer);
				
			}
			out.flush();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();*/
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

	}

}
